package com.itheima.commons.template;

import com.alibaba.fastjson.JSON;
import com.itheima.commons.properties.HuanXinProperties;
import com.itheima.commons.vo.HuanXinUser;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

import java.util.*;

/**
 * @author 阿鹏
 * @date 2021/2/2 17:31
 */

public class HuanXinTemplate {

    private HuanXinProperties properties;
    private RestTemplate restTemplate;
    private String token;
    private long expire = 0L;

    public HuanXinTemplate(HuanXinProperties properties) {
        this.properties = properties;
        this.restTemplate = new RestTemplate();
    }

    /**
     * 环信-注册用户
     * @param userId 用户id
     * @return 是否注册成功
     */
    public boolean register(Long userId){
        String url = properties.getHuanXinUrl() + "/users";

        //请求头信息
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.add("Content-Type", "application/json");
        httpHeaders.add("Authorization", "Bearer " + getToken());

        List<HuanXinUser> huanXinUsers = new ArrayList<>();
        huanXinUsers.add(new HuanXinUser(userId.toString(), "123456"));

        try {
            HttpEntity<String> httpEntity = new HttpEntity(JSON.toJSONString(huanXinUsers), httpHeaders);
            //发起请求
            ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, httpEntity, String.class);
            return responseEntity.getStatusCode().value() == 200;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 环信-添加好友
     * @param userId 用户id
     * @param friendId 好友id
     */
    public boolean contactUsers(Long userId, Long friendId) {

        String targetUrl = properties.getHuanXinUrl()+ "/users/" + userId + "/contacts/users/" + friendId;

        // 请求头
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", "application/json ");
        headers.add("Authorization", "Bearer " + getToken());

        try {
            HttpEntity<String> httpEntity = new HttpEntity<>(headers);
            ResponseEntity<String> responseEntity = restTemplate.postForEntity(targetUrl, httpEntity, String.class);
            return responseEntity.getStatusCode().value() == 200;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 环信-发送消息
     */
    public boolean sendMsg(String target, String msg){
        try {
            //API接口地址
            String url = properties.getHuanXinUrl() + "/messages";

            //设置请求头
            HttpHeaders headers = new HttpHeaders();
            headers.add("Content-Type", "application/json");
            headers.add("Authorization", "Bearer " + getToken());

            //请求参数。
            Map<String, Object> requestParam = new HashMap<>();
            //   target_type：users，表示给用户发消息。
            requestParam.put("target_type", "users");
            //   target，发送给谁，要求使用数组
            requestParam.put("target", Arrays.asList(target));
            //   type，消息类型。txt文本消息，img：图片消息，loc：位置消息，audio：语音消息，video：视频消息，file：文件消息
            requestParam.put("type", "txt");
            //   消息发送者;无此字段Server会默认设置为“from”:“admin”，有from字段但值为空串(“”)时请求失败
            //requestParam.put("from", null);
            //   发送的消息内容
            Map<String, Object> msgContent = new HashMap<>();
            msgContent.put("type", "txt");
            msgContent.put("msg", msg);
            requestParam.put("msg", msgContent);


            //封装请求数据实体
            HttpEntity<Map> httpEntity = new HttpEntity<>(requestParam, headers);
            //调用环信API，发送信息
            ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, httpEntity, String.class);
            return responseEntity.getStatusCode().value() == 200;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }


    /**
     * 获取token
     */
    private String getToken() {
        long now = System.currentTimeMillis();
        if(now > expire) {
            //环信，获取token的API接口地址
            String url = this.properties.getUrl() + this.properties.getOrgName() + "/" + this.properties.getAppName() + "/token";

            //请求体
            Map<String, Object> param = new HashMap<>();
            param.put("grant_type", "client_credentials");
            param.put("client_id", this.properties.getClientId());
            param.put("client_secret", this.properties.getClientSecret());

            ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, param, String.class);
            String body = responseEntity.getBody();

            Map map1 = JSON.parseObject(body, Map.class);
            token = (String) map1.get("access_token");
            expire = System.currentTimeMillis() + 24 * 60 * 60 * 1000;
        }
        return token;
    }
}
